package com.lx.chong.utils;

import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author: yzq
 * @date: 2019/1/7
 * @tableName:
 */
public class DownloadUtil {

    /**
     * 下载
     *
     * @param resp
     * @param path
     * @param downloadName
     * @throws Exception
     */
    public static void commonDownload(HttpServletResponse resp, String path, String downloadName) throws Exception {
        URL urlfile;
        HttpURLConnection httpUrl;
        urlfile = new URL(path);
        httpUrl = (HttpURLConnection) urlfile.openConnection();
        httpUrl.connect();
        InputStream inputStream = httpUrl.getInputStream();
        resp.reset();
        resp.setContentType(httpUrl.getContentType());
        resp.setCharacterEncoding("utf-8");
        resp.setContentLength(httpUrl.getContentLength());
        resp.setHeader("Content-Disposition", "attachment;filename=" + downloadName);
        resp.setHeader("Access-Control-Allow-Origin", "*");
        OutputStream os;
        os = resp.getOutputStream();
        IOUtils.copy(inputStream, os);
    }
}
